package com.pengheng.netty.server;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class MyDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        if (in.readableBytes() < 8) {
            log.error("暂未获取到合法报文");
            return;
        }
        in.markReaderIndex();

        //跳过报文头
        in.skipBytes(2);
        //报文类型
        var msgType = in.readUnsignedByte();

        if (msgType == 48) { //排队信息上报
            var title = 2;
            var type = 1;
            var time = 6;
            //跳过时间
            in.skipBytes(6);
            var targetNum = in.readUnsignedByte();
            var contentLength = 2 + 2 + 4 + 4 + 1 + 2 + 1 + 1 + 1 + 1;

            var totalContentSize = contentLength * targetNum;
            var totalSize = title + type + time + 1 + totalContentSize + 1;

            in.resetReaderIndex();
            if (in.readableBytes() < totalSize) {
                log.error("未获取到完整数据包");
                return;
            }
            ByteBuf buf = in.readBytes(totalSize);
            out.add(buf);
        } else {//报文长度
            var msgLength = in.readUnsignedShortLE();
            in.resetReaderIndex();
            if (in.readableBytes() < msgLength) {
                log.error("未获取到完整数据包");
                return;
            }
            ByteBuf buf = in.readBytes(msgLength);
            out.add(buf);


        }

    }
}
